package org.onvivals.admin.module.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import org.onvivals.admin.module.auth.service.ICaptchaService;
import org.onvivals.common.utils.RedisUtils;
import com.wf.captcha.ArithmeticCaptcha;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaServiceImpl implements ICaptchaService {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public Map<String, Object> create(HttpServletResponse response) {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = "";
        try {
            result = Double.valueOf(Double.parseDouble(captcha.text())).intValue() + "";
        } catch (Exception e) {
            result = captcha.text();
        }
        log.info("验证码结果：{} ", result);
        String uuid = IdUtil.simpleUUID();
        // 保存
        redisUtils.set(uuid, result, 5, TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return imgResult;

    }
}
